﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace Home.Haushalt
{
    /// <summary>
    /// 
    /// </summary>
    public partial class JournalForm : Form
    {
        /// <summary></summary>
        public CheckBox CbErrorsOnly { get { return cbErrorsOnly; } }
        /// <summary></summary>
        public CheckBox CbDev { get { return cbDev; } }
        /// <summary></summary>
        public CheckBox CbSqlExecute { get { return cbSqlExecute; } }
        /// <summary></summary>
        public CheckBox CbSqlMessage { get { return cbSqlMessage; } }
        /// <summary></summary>
        public CheckBox CbSqlScript { get { return cbSqlScript; } }

        /// <summary></summary>
        private bool _ctrlPressed = false;

        /// <summary></summary>
        private bool _shiftPressed = false;

        /// <summary></summary>
        private bool _assignAdded = true;

        /// <summary></summary>
        private DataView _dv = null;

        /// <summary></summary>
        private DataTable _currentTable;

        /// <summary>
        /// 
        /// </summary>
        public JournalForm()
        {
            InitializeComponent();

            Journal.OnLabelModified += new EventHandler(Journal_OnLabelModified);

            _dv = new DataView(Journal.LogTable);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void journalGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (!_assignAdded)
                return;

            journalGrid.ClearSelection();
            journalGrid.CurrentCell = null;
            for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++)
            {
                AssignRow(i);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Journal_OnLabelModified(object sender, EventArgs e)
        {
            string selectedItem = (cbLabels.SelectedItem == null) ? "Alle" : cbLabels.SelectedItem.ToString();

            cbLabels.Items.Clear();

            cbLabels.Items.Add("Alle");
            cbLabels.Items.AddRange(Journal.Labels.ToArray());

            cbLabels.SelectedItem = selectedItem;

            cbLabels.SelectedIndex = 0;
            _currentTable = null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="rowIndex"></param>
        private void AssignRow(int rowIndex)
        {
            DataGridViewRow row = journalGrid.Rows[rowIndex];

            string result = row.Cells[Journal.COLUMNNAME_ACTIONRESULT].Value.ToString();
            string type = row.Cells[Journal.COLUMNNAME_ACTIONTYPE].Value.ToString();

            row.Visible = !cbErrorsOnly.Checked || (cbErrorsOnly.Checked && result != ActionResult.Ok.ToString());
            row.Visible = row.Visible &&
                            (cbDev.Checked && type == ActionType.Dev.ToString()) ||
                            (cbSqlScript.Checked && type == ActionType.SqlScript.ToString()) ||
                            (cbSqlExecute.Checked && type == ActionType.SqlExecute.ToString()) ||
                            (cbSqlMessage.Checked && type == ActionType.SqlMessage.ToString());

            row.DefaultCellStyle.ForeColor = (result == ActionResult.Ok.ToString()) ? Color.Black : ((result == ActionResult.Nok.ToString()) ? Color.Maroon : Color.Blue);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JournalForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JournalForm_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.journalGrid.Columns.Clear();
                this.journalGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
                colTime,colActionResult,colActionType,colComments,colSender,colAction,colException});
                colTime.DisplayIndex = 0;
                colActionResult.DisplayIndex = 1;
                colActionType.DisplayIndex = 2;
                colComments.DisplayIndex = 3;
                colSender.DisplayIndex = 4;
                colAction.DisplayIndex = 5;
                colException.DisplayIndex = 6;

                _assignAdded = false;

                journalGrid.DataSource = _dv;

                _assignAdded = true;
            }
            else
            {
                journalGrid.DataSource = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFilterApply_Click(object sender, EventArgs e)
        {
            Apply();
        }

        /// <summary>
        /// 
        /// </summary>
        public void Apply()
        {
            _dv.RowFilter = ((cbErrorsOnly.Checked) ? Journal.COLUMNNAME_ACTIONRESULT + "<>'" + ActionResult.Ok.ToString() + "' and " : "") +
                Journal.COLUMNNAME_ACTIONTYPE + " in (" +
                (cbDev.Checked ? "'" + ActionType.Dev.ToString() + "'," : "'-',") +
                (cbSqlScript.Checked ? "'" + ActionType.SqlScript.ToString() + "'," : "'-',") +
                (cbSqlExecute.Checked ? "'" + ActionType.SqlExecute.ToString() + "'," : "'-',") +
                (cbSqlMessage.Checked ? "'" + ActionType.SqlMessage.ToString() + "'" : "'-'") +
                ")";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void journalGrid_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            JournalFormDetails jfd = new JournalFormDetails(journalGrid);
            jfd.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        public new void Show()
        {
            Show(false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="showFilter"></param>
        public void Show(bool showFilter)
        {
            pnlFilter.Visible = showFilter;
            base.Show();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JournalForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
                _ctrlPressed = true;
            if (e.Shift)
                _shiftPressed = true;

            if (_ctrlPressed && _shiftPressed && e.KeyCode == Keys.F)
                pnlFilter.Visible = !pnlFilter.Visible;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JournalForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control)
                _ctrlPressed = false;
            if (e.Shift)
                _shiftPressed = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbLabels_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_currentTable == null)
                _currentTable = Journal.LogTable;

            if (cbLabels.SelectedIndex > 0)
                _dv = new DataView(Journal.GetLabel(cbLabels.SelectedItem.ToString()));
            else
                _dv = new DataView(_currentTable);


            JournalForm_VisibleChanged(sender, e);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchWord_Click(object sender, EventArgs e)
        {
            btnSearchWord.Enabled = GoToRow(txtSearchWord.Text, 1);
            btnSearchWordPrev.Enabled = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchWordPrev_Click(object sender, EventArgs e)
        {
            btnSearchWordPrev.Enabled = GoToRow(txtSearchWord.Text, -1);
            btnSearchWord.Enabled = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchWord"></param>
        /// <param name="direction">1 = vorwärts; -1 = rückwärts</param>
        /// <returns>Gefunden</returns>
        private bool GoToRow(string searchWord, int direction)
        {
            if (journalGrid.SelectedRows.Count == 0)
                return false;

            bool found = false;

            for (int i = journalGrid.SelectedRows[0].Index + 1 * direction; i < journalGrid.Rows.Count; i = i + 1 * direction)
            {
                if (i < 0 || i > journalGrid.Rows.Count - 1)
                    break;

                DataGridViewRow row = journalGrid.Rows[i];
                if (row.Visible)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value.ToString().ToUpper().IndexOf(searchWord.ToUpper()) > -1)
                        {
                            journalGrid.ClearSelection();
                            row.Selected = true;
                            journalGrid.FirstDisplayedScrollingRowIndex = i;
                            found = true;
                            break;
                        }
                    }
                    if (found)
                        break;
                }
            }

            return found;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSearchWord_TextChanged(object sender, EventArgs e)
        {
            btnSearchWord.Enabled = btnSearchWordPrev.Enabled = txtSearchWord.Text.Length != 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenLogFile_Click(object sender, EventArgs e)
        {
            if (File.Exists(Journal.LogFullFileName))
            {
                Process.Start(Journal.LogFullFileName);
            }
            else
            {
                MessageBox.Show("Log-Datei [" + Journal.LogFullFileName + "] ist nicht gefunden");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenLogFolder_Click(object sender, EventArgs e)
        {
            if (File.Exists(Journal.LogFullFileName))
            {
                Process explorerResultProcess = new Process();
                explorerResultProcess.StartInfo.UseShellExecute = true;
                explorerResultProcess.StartInfo.FileName = "explorer.exe";
                explorerResultProcess.StartInfo.Arguments = string.Format("/e,/select,\"{0}\"", Journal.LogFullFileName);
                explorerResultProcess.Start();

            }
            else
            {
                MessageBox.Show("Log-Datei [" + Journal.LogFullFileName + "] ist nicht gefunden");
            }
        }
    }
}
